﻿using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Xml;
using LitJson;
using MediaPortal.GUI.Library;
using System.Threading;
using System.Net;
using System.ComponentModel;
using System.IO; 

namespace MediaPortal.Plugins.Trailers.Providers
{
    public class MovieMazeTrailerPage
    {
        
        private const string trailerRegExp = "<td.*?>(?<resolution>\\d*? x \\d*?)<\\/td><td.*?>(?<filesize>.*?)<\\/td><td.*?>.*?<\\/td><td.*?>.*?(?<url>\\/media\\/trailer\\/delivery\\/.*?)\".*?<\\/td>";

        public Trailer fetchTrailer(string key)
        {
            Trailer trailer = new Trailer();

            string url = MovieMazeTrailers.urlBase + key;
            string html = string.Empty;

            MovieMazeTrailerWebClient client = new MovieMazeTrailerWebClient();
            client.GetWebPage(url, MovieMazeTrailers.urlBase, out html);
            
            trailer.Title = getTitle(html);
            trailer.Poster = getPoster(html);
            trailer.Thumb = getPoster(html);
            trailer.Genres.Add(getGenre(html));
            trailer.Description = client.StripHTML(getDescription(html));

            MovieMazeDetailsPage detailsPage = new MovieMazeDetailsPage(getDetailsPage(html));
            trailer.ReleaseDate = detailsPage.getReleaseDate_DE();
            trailer.Director = detailsPage.getDirector();
            detailsPage.getCast(trailer.Cast);
            trailer.Rating = detailsPage.getRating();

            string trailerNameRegExp = "<b style=\"font-weight:bold;\">(?<trailername>.*?)<\\/b><br \\/>";
            string trailerRegionsRegExp = ".(?=" + trailerNameRegExp + ")";

            string trailerLanguageRegExp = "flag_(?<language>.*)\\.";
            string resolutionRegionRegExp = ".(?=" + trailerLanguageRegExp + ")";

            foreach (string region in Regex.Split(html, @trailerRegionsRegExp))
            {
                string trailername = Regex.Match(region, @trailerNameRegExp).Groups["trailername"].Value.ToString();

                foreach (string resolutionRegion in Regex.Split(region, @resolutionRegionRegExp))
                {
                    string language = Regex.Match(resolutionRegion, @trailerLanguageRegExp).Groups["language"].Value.ToString();
                    if (language.Length > 0)
                    {
                        string label = trailername + " (" + parseLanguage(language) + ")";

                        MatchCollection resolutionMatchC = Regex.Matches(resolutionRegion, @trailerRegExp);

                        foreach (Match resolutionMatch in resolutionMatchC)
                        {
                            Video video = trailer.Media.Set(label);
                            video.Label = label;

                            string resolution = resolutionMatch.Groups["resolution"].Value.ToString();
                            string videourl = resolutionMatch.Groups["url"].Value.ToString();
                            VideoQuality quality = parseVideoQuality(resolution);
                            Uri videoUri = new Uri(MovieMazeTrailers.urlBase + videourl);
                            video.Size[quality] = videoUri;
                        }
                    }
                }
            }


            return trailer;
        }

        private string getDetailsPage(string html)
        {
            string detailsPageRegExp = "<a href=\"(?<detailspage>\\/filme\\/.*?\\.html)\"";
            return Regex.Match(html, @detailsPageRegExp).Groups["detailspage"].Value.ToString();
        }

        private string getTitle(string html)
        {
            string titleRegExp = "<h1>(?<title>.*?)<\\/h1>";
            return Regex.Match(html, @titleRegExp).Groups["title"].Value.ToString();
        }

        private string getPoster(string html)
        {
            string posterRegExp = "<img src=\"(?<posterurl>\\/filme.*?\\/poster.*?\\.jpg)\"";
            return MovieMazeTrailers.urlBase + Regex.Match(html, @posterRegExp).Groups["posterurl"].Value.ToString();
        }

        private string getGenre(string html)
        {
            string genreRegExp = "Genre:<\\/b>(?<genre>.*?)<\\/td>";
            return Regex.Match(html, @genreRegExp).Groups["genre"].Value.ToString().Trim();
        }

        private string getDescription(string html)
        {
            string descriptionRegExp = "! -->(?<description>.*?)<\\/span>";
            return Regex.Match(html, @descriptionRegExp).Groups["description"].Value.ToString().Trim();
        }

        private VideoQuality parseVideoQuality(string quality)
        {
            VideoQuality result = VideoQuality.UNKNOWN;

            try
            {
                String regexp = "(?<resolutionx>\\d*?) x (?<resolutiony>\\d*)";

                Match m = Regex.Match(quality, @regexp);
                String sX = m.Groups["resolutionx"].Value.ToString();
                String sY = m.Groups["resolutiony"].Value.ToString();

                int x = Convert.ToInt32(sX);
                int y = Convert.ToInt32(sY);

                if (x > 1800)
                {
                    result = VideoQuality.FULLHD;
                }
                else if (x > 1000)
                {
                    result = VideoQuality.HD720;
                }
                else if (x > 480)
                {
                    result = VideoQuality.LARGE;
                }
                else if (x > 400)
                {
                    result = VideoQuality.HD480;
                }
                else if (x > 300)
                {
                    result = VideoQuality.MEDIUM;
                }
                else if (x > 100)
                {
                    result = VideoQuality.SMALL;
                }

            }
            catch (Exception e)
            {
                Log.Info("[MyTrailers][MovieMaze Trailers] parseVideoQuality: {0}", e.Message);
            }
            return result;
        }

        private string parseLanguage(string code)
        {
            switch (code)
            {
                case "de":
                    return "german";
                case "en":
                    return "english";
                default:
                    return "unknown";
            }
        }
    }
}